#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>

#include "Log.hpp"
#include "InetAddr.hpp"
#include "Socket.hpp"

using namespace socket_ns;

class TcpServer;

using io_server_t = std::function<void (socket_sptr sockfd, InetAddr client)>;

class ThreadData
{
public:
    ThreadData(socket_sptr sockfd, InetAddr clientaddr, TcpServer *self)
        : _sockfd(sockfd)
        , _clientaddr(clientaddr)
        , _self(self)
    {}

public:
    socket_sptr _sockfd;
    InetAddr _clientaddr;
    TcpServer *_self;
};

class TcpServer
{
public:
    TcpServer(uint16_t port, io_server_t service)
        : _localaddr("0", port)
        , _listensock(std::make_unique<TcpSocket>())
        , _service(service)
        , _isrunning(false)
    {
        _listensock->BuildListenSocket(_localaddr);
    }

    static void *HandlerSock(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData*>(args);
        td->_self->_service(td->_sockfd, td->_clientaddr);
        ::close(td->_sockfd->SockFd());
        delete td;
        return nullptr;
    }
    void Loop()
    {
        _isrunning = true;
        while(_isrunning)
        {
            InetAddr peeraddr;
            std::cout<<"等待！\n";
            socket_sptr normalsock = _listensock->Accepter(&peeraddr);
            if(normalsock == nullptr) continue;

            pthread_t t;
            ThreadData *td = new ThreadData(normalsock, peeraddr, this);
            pthread_create(&t, nullptr, HandlerSock, td);   // 线程分离 
        }
        _isrunning = false;
    }

    ~TcpServer()
    {}

private:
    InetAddr _localaddr;
    std::unique_ptr<Socket> _listensock;
    bool _isrunning;

    io_server_t _service;
};